<!--
 * @Author: early-autumn
 * @Date: 2020-05-27 13:40:56
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-05 19:42:44
-->
<template>
  <el-dialog title="修改TC" width="500px" :visible="value" @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" inline label-width="88px">
      <el-form-item label="选择TC" prop="tcId">
        <el-select v-model="form.tcId" placeholder="请选择TC">
          <el-option
            v-for="tc in tcOptions"
            :key="tc.userId"
            :label="tc.userName"
            :value="tc.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" style="width: 300px" type="textarea" />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import { listStaff } from '@/api/services/common'
import { updateAppointment } from '@/api/services/appointment'

export default {
  name: 'ModifyTC',
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({
        id: 0,
        tcId: 0,
      }),
    },
  },
  data() {
    return {
      loading: false,
      tcOptions: [],
      form: {
        tcId: 0,
        remarks: '',
      },
      rules: {
        tcId: { required: true, message: '请选择TC', trigger: 'blur' },
      },
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
      } else {
        this.$refs.form.resetFields()
      }
    },
  },
  mounted() {
    this.getListStaff()
  },
  methods: {
    init() {
      this.form.tcId = +this.data.tcId
      this.form.remarks = ''
    },
    /**
     * 获取TC列表
     */
    async getListStaff() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })

      this.tcOptions = data
    },

    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        try {
          if (!valid) {
            return
          }

          let tcName

          this.tcOptions.forEach((tc) => {
            if (tc.userId === this.form.tcId) {
              tcName = tc.userName
            }
          })

          this.loading = true
          await updateAppointment({
            id: this.data.id,
            tcName,
            ...this.form,
          })
          this.msgSuccess('修改成功')
          this.handleClose()
          this.$emit('ok')
        } finally {
          this.loading = false
        }
      })
    },

    handleClose() {
      this.$emit('close', false)
    },
  },
}
</script>

<style></style>
